package logic

import (
	"context"
	"encoding/json"
	"hippo-fresh/model/cache"
	"hippo-fresh/model/mysql"
	"time"

	"hippo-fresh/hipporpc/hipporpc"
	"hippo-fresh/hipporpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type ShopListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewShopListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ShopListLogic {
	return &ShopListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ShopListLogic) ShopList(in *hipporpc.ShopListRequest) (*hipporpc.ShopListResponse, error) {
	// todo: add your logic here and delete this line

	var shops []mysql.Shop

	result, _ := cache.Rdb.Get(l.ctx, "shopList").Result()
	if result == "" {
		mysql.DB.Debug().Scopes(mysql.Paginate(int(in.Page), int(in.Size))).Find(&shops)
		jsonData, _ := json.Marshal(shops)
		cache.Rdb.Set(l.ctx, "shopList", jsonData, time.Minute*30)
	} else {
		json.Unmarshal([]byte(result), &shops)
	}

	var shopList []*hipporpc.ShopList

	for _, shop := range shops {
		list := hipporpc.ShopList{
			Title:   shop.Title,
			Price:   float32(shop.Price),
			Address: shop.Address,
			ClassId: int64(shop.ClassID),
		}
		shopList = append(shopList, &list)
	}

	return &hipporpc.ShopListResponse{
		List: shopList,
	}, nil
}
